package cn.youth996.nav.service.impl;

import cn.youth996.nav.service.OsrmService;
import cn.youth996.nav.util.CoordinateTransformUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Zhan Xinjian
 * @date 2025/5/12
 */
@Service
public class OsrmServiceImpl implements OsrmService {
    private static final String OSRM_URL = "http://dev10.youth996.cn:8050/route/v1/driving/";

    @Override
    public String getRoute(String from, String to) throws IOException {
        String[] fromParts = from.split(",");
        String[] toParts = to.split(",");

        // 将 GCJ-02 转为 WGS-84
        double[] fromWGS = CoordinateTransformUtils.gcj02ToWgs84(Double.parseDouble(fromParts[0]), Double.parseDouble(fromParts[1]));
        double[] toWGS = CoordinateTransformUtils.gcj02ToWgs84(Double.parseDouble(toParts[0]), Double.parseDouble(toParts[1]));

        String coords = String.format("%f,%f;%f,%f",
                fromWGS[1], fromWGS[0],  // WGS84：lon,lat
                toWGS[1], toWGS[0]);

        String url = OSRM_URL + coords + "?overview=full&geometries=geojson";

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(request)) {
                // 原始 OSRM 响应
                String responseJson = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                ObjectMapper mapper = new ObjectMapper();
                ObjectNode rootNode = (ObjectNode) mapper.readTree(responseJson);
                ArrayNode coordsArray = (ArrayNode) rootNode.at("/routes/0/geometry/coordinates");

                for (int i = 0; i < coordsArray.size(); i++) {
                    ArrayNode point = (ArrayNode) coordsArray.get(i);
                    double lon = point.get(0).asDouble();
                    double lat = point.get(1).asDouble();

                    double[] gcj = CoordinateTransformUtils.transform(lat, lon);
                    point.set(0, mapper.getNodeFactory().numberNode(gcj[1])); // lon
                    point.set(1, mapper.getNodeFactory().numberNode(gcj[0])); // lat
                }

                // 最终返回给前端的 JSON 字符串
                return mapper.writeValueAsString(rootNode);
            }
        }
    }
}
